<script lang="tsx">
import { defineComponent, ref } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { UsersRound, ContactRound } from '@vben/icons';
import { $t } from '@vben/locales';
import { getTeamInfoPageApi, exportTeamInfoApi } from '#/api/competition/team-info';
import { usePage } from '#/hooks/page/usePage';
import { teamTypeOptions } from './modules/team-info/const';
import { provinceCityOptions } from '@vben/utils';
import TeamMembers from './modules/team-info/team-members.vue';

export default defineComponent({
  name: 'TeamInfo',
  setup() {
    const router = useRouter();
    const exportLoading = ref(false);
    const showMembers = ref(false);
    const currentTeamData = ref({});

    const API = {
      get: (data: any) => {
        let params = { ...data };
        console.log('params:', params);
        if (params.createTime?.length) {
          let [startTime, endTime] = params.createTime;
          params.createStartTime = startTime
          params.createEndTime = endTime
          delete params.createTime;
        }
        if (params.province?.length) {
          const [province, city] = params.province;
          const provinceObj = provinceCityOptions.find(item => item.value === province);
          const cityObj = provinceObj?.children?.find(item => item.value === city);
          params.province = provinceObj?.label;
          params.city = cityObj?.label;
        }
        return getTeamInfoPageApi(params)
      }
    };

    // 查询配置
    const queryColumns = [
      {
        prop: 'name',
        label: $t('competition.teamName'),
        type: 'input',
        placeholder: $t('common.inputPhTxt', [$t('competition.teamName')]),
      },
      {
        prop: 'type',
        label: $t('competition.teamInfo.teamType'),
        type: 'select',
        placeholder: $t('common.selectPhTxt', [$t('competition.teamInfo.teamType')]),
        options: teamTypeOptions,
      },
      {
        prop: 'organName',
        label: $t('competition.organizationName'),
        type: 'input',
        placeholder: $t('common.inputPhTxt', [$t('competition.organizationName')]),
      },
      {
        prop: 'province',
        label: $t('competition.teamInfo.province'),
        type: 'custom',
        render: (model: any) => (
          <el-cascader
            v-model={model.province}
            options={provinceCityOptions}
            placeholder={$t('common.selectPhTxt', [$t('competition.teamInfo.province')])}
            clearable
            filterable
            expand-trigger="hover"
            check-strictly={false}
            emit-path={true}
            style="width: 100%"
          />
        )
      },
      {
        prop: 'compId',
        label: $t('competition.teamInfo.belongCompetition'),
        type: 'input',
        placeholder: $t('common.inputPhTxt', [$t('competition.teamInfo.belongCompetition')]),
      },
      {
        prop: 'createTime',
        label: $t('common.createTimeTxt'),
        type: 'daterange',
        component: 'el-date-picker',
        rangeSeparator: $t('common.rangeSeparatorTxt'),
        unlinkPanels: true,
        showIcon: true,
        startPlaceholder: $t('common.startTimeTxt'),
        endPlaceholder: $t('common.endTimeTxt'),
        format: "YYYY-MM-DD",
        'value-format': "YYYY-MM-DD",
        'default-time': [
          new Date(2000, 1, 1, 0, 0, 0),
          new Date(2000, 1, 1, 23, 59, 59),
        ]
      },
    ];

    // 表格列配置
    const columns = [
      {
        type: 'selection',
        width: 50,
        align: 'center',
        prop: 'selection'
      },
      {
        type: 'index',
        label: $t('common.numberIdxTxt'),
        width: 60,
        align: 'center',
        prop: 'index'
      },
      {
        prop: 'name',
        label: $t('competition.teamName'),
        minWidth: 250,
        showOverflowTooltip: true,
        formatter: (row: any) => {
          return (
            <span>
              {row.name || '--'}
            </span>
          );
        }
      },
      {
        prop: 'type',
        label: $t('competition.teamInfo.teamType'),
        minWidth: 100,
        formatter: (row: any) => {
          const option = teamTypeOptions.find(opt => opt.value === row.type);
          return (
            <span>
              {option ? option.label : row.type || '--'}
            </span>
          );
        }
      },
      {
        prop: 'organName',
        label: $t('competition.organizationName'),
        minWidth: 200,
        showOverflowTooltip: true,
        formatter: (row: any) => {
          return (
            <span>
              {row.organName || '--'}
            </span>
          );
        }
      },
      {
        prop: 'provinceCity',
        label: $t('competition.teamInfo.province'),
        minWidth: 150,
        showOverflowTooltip: true,
        formatter: (row: any) => {
          return (
            <span>
              {row.provinceCity || '--'}
            </span>
          );
        }
      },
      {
        prop: 'captain',
        label: $t('competition.teamInfo.captainName'),
        minWidth: 120,
        showOverflowTooltip: true,
        formatter: (row: any) => {
          return (
            <span>
              {row.captain || '--'}
            </span>
          );
        }
      },
      {
        prop: 'memberCount',
        label: $t('competition.teamInfo.memberCount'),
        minWidth: 100,
        formatter: (row: any) => {
          return (
            <span>
              {row.memberCount || '--'}
            </span>
          );
        }
      },
      {
        prop: 'compName',
        label: $t('competition.teamInfo.belongCompetition'),
        minWidth: 250,
        showOverflowTooltip: true,
        formatter: (row: any) => {
          return (
            <span>
              {row.compName || '--'}
            </span>
          );
        }
      },
      {
        prop: 'createTime',
        label: $t('common.createTimeTxt'),
        minWidth: 180,
        showOverflowTooltip: true,
        formatter: (row: any) => {
          return (
            <span>
              {row.createTime || '--'}
            </span>
          );
        }
      },
    ];


    // 操作按钮配置
    const commands = [
      {
        key: 'link',
        width: 40,
        label: $t('competition.teamInfo.registerInfo'),
        icon: ContactRound,
        render: (row: any, index?: number) => {
          return (
            <el-tooltip
              effect="dark"
              content={$t('competition.teamInfo.registerInfo')}
              show-after={600}
              placement="top"
            >
              <el-button
                link
                icon={ContactRound}
                onClick={() => tableHandle('link', row, index)}
              />
            </el-tooltip>
          );
        },
      },
      {
        key: 'detail',
        width: 40,
        label: $t('competition.teamInfo.teamMembers'),
        icon: UsersRound,
        render: (row: any, index?: number) => {
          return (
            <el-tooltip
              effect="dark"
              content={$t('competition.teamInfo.teamMembers')}
              show-after={600}
              placement="top"
            >
              <el-button
                link
                icon={UsersRound}
                onClick={() => tableHandle('detail', row, index)}
              />
            </el-tooltip>
          );
        },
      },
    ];

    // 自定义操作处理
    const handleCommand = (action: string, row: any, index?: number) => {
      console.log('action:', action);
      console.log('row:', index);
      if (action === 'link') {
        // 路由跳转到报名信息页面
        router.push({
          path: '/competition/registrationInfo',
          query: {
            teamId: row.id
          }
        });
      } else if (action === 'detail') {
        // 查看详情
        currentTeamData.value = { ...row };
        showMembers.value = true;
      }
    };

    const { render, tableHandle, selection } = usePage({
      API,
      operateProps: {
        fixed: 'right',
      },
      columns,
      queryColumns,
      commands,
      handleCommand,
    });

    // 导出功能
    const handleExport = async () => {
      if (selection.value.length === 0) {
        ElMessage.error($t('common.selectPhTxt', [$t('competition.teamInfo.exportTeamInfo')]));
        return;
      }

      try {
        const params = { idList: selection.value.map((item: any) => item.id) }
        exportLoading.value = true;
        const response = await exportTeamInfoApi(params) as any;
        // 验证响应是否为有效的Excel文件
        if (!response || response.data.size === 0) {
          throw new Error($t('common.exportFailed'));
        }

        // 检查MIME类型
        const validTypes = [
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
          'application/vnd.ms-excel',
          'application/octet-stream'
        ];

        if (!validTypes.includes(response.data.type)) {
          console.warn('Unexpected file type:', response.data.type);
        }

        // 创建下载链接
        const url = window.URL.createObjectURL(response.data);
        const link = document.createElement('a');
        link.href = url;

        // 根据MIME类型设置文件名
        const timestamp = new Date().toISOString().split('T')[0];
        let fileName = `团队信息_${timestamp}`;

        if (response.data.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
          fileName += '.xlsx';
        } else if (response.data.type === 'application/vnd.ms-excel') {
          fileName += '.xls';
        } else {
          // 默认使用.xlsx扩展名
          fileName += '.xlsx';
        }

        link.download = fileName;

        // 触发下载
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);

        exportLoading.value = false;
        ElMessage.success($t('common.exportSuccess'));
      } catch (error) {
        exportLoading.value = false;
        ElMessage.error($t('common.exportFailed'));
      }
    };

    const handleMembersCancel = () => {
      showMembers.value = false;
    };

    return () => (
      <div class="team-info-page">
        {
          render({
            header: (
              <div class="flex justify-between items-center">
                <el-button type="primary" onClick={handleExport} loading={exportLoading.value}>
                  {$t('common.exportTxt')}
                </el-button>
              </div>
            ),
            table: {
              prefix: () => [] // 覆盖默认的 prefix，不包含 serialColumn
            }
          })
        }
        <TeamMembers
          modelValue={showMembers.value}
          onUpdate:modelValue={(val: boolean) => showMembers.value = val}
          onCancel={handleMembersCancel}
          teamData={currentTeamData.value}
        />
      </div>
    );
  }
});
</script>
<style lang="scss" scoped>
:deep(.el-date-editor .el-range__icon) {
  display: none;
}
</style>
